package com.enjoyor.soa.traffic.frame.dubbo;

import com.alibaba.dubbo.rpc.*;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class AuthorityFilter implements Filter{
    
    private static final Logger logger = Logger.getLogger(AuthorityFilter.class);
    
    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {

        Properties prop = new Properties();
        InputStream in = AuthorityFilter.class.getResourceAsStream("/ipwhitelist.properties");
        String clientIp = RpcContext.getContext().getRemoteHost();
        try {
            prop.load(in); 
            boolean enable=Boolean.parseBoolean(prop.getProperty("dubbo.server.filter.enable", "false"));
            String ipwhitelist = prop.getProperty("dubbo.server.filter.allowedIps");
            
            if(!enable) {
                logger.info("白名单禁用");
                return invoker.invoke(invocation);
            }
            
            if (ipwhitelist.contains(clientIp)) {
                return invoker.invoke(invocation);
            } else {                            
                return new RpcResult("无dubbo访问权限，白名单中不包含此IP");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (RpcException e) {
            throw e;
        } catch (Throwable t) {
            throw new RpcException(t.getMessage(), t);
        }
        return invoker.invoke(invocation);
    }

}
